#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QNetworkInterface>
#include <QHostAddress>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
    tcpServer = NULL;
    tcpSocket = NULL;

    QList<QHostAddress> addr = QNetworkInterface::allAddresses();

    ui->showInfo->appendPlainText(tr("IP Address"));
    for(int i=0;i<addr.size();i++)
        ui->showInfo->appendPlainText(addr.at(i).toString());

    ui->showInfo->appendPlainText(tr("Port:8123"));
    QDir::setCurrent(tr("/mnt/sdcard"));
    
    isOpen = false;
    lightOn = false;
}

MainWindow::~MainWindow()
{
    delete ui;
}



bool MainWindow::server_recv(char recv_buf[])
{
    char send_buf[1024];
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("GB2312"));
    QString str=QString::fromLocal8Bit(recv_buf);
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
    QByteArray tstr = str.toLocal8Bit();
    char *data = tstr.data();
    if(cmp_str(data,"#*#cd"))
    {
        ui->showInfo->appendPlainText(str);
        char dir[1000];
        strcpy(dir,&data[6]);
        if(strlen(dir)>0)
            QDir::setCurrent(tr(dir));

        QString tdir = QDir::currentPath();
        QTextCodec::setCodecForLocale(QTextCodec::codecForName("GB2312"));
        QByteArray temp1 = tdir.toLocal8Bit();
        char *path = temp1.data();
        sprintf(send_buf,"#*#dir %s",path);
        QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
        this->send_str(send_buf);

    }
    else if(cmp_str(data,"#*#rfilelist")) {
        ui->showInfo->appendPlainText(str);
        char srcFilename[1000];
        getSubStr(data,srcFilename,1);
        sendFileList(srcFilename);
    }

    else if(cmp_str(data,"#*#recvfile")) {
        ui->showInfo->appendPlainText(str);
        char srcFilename[1000];
        getSubStr(data,srcFilename,1);
        sendFile(srcFilename);
    }
    //recv client's send file
    else if(cmp_str(recv_buf,"#*#clientfile")) {
        ui->showInfo->appendPlainText(str);
        char dstFilename[1000];
        getSubStr(data,dstFilename,1);
        detectName(dstFilename);
        rfp=fopen(dstFilename,"wb");
    }
    else if(cmp_str(recv_buf,"#*#file"))
    {
        int size=0;
        int place=0;
        place=getMessageSize(data,size);
        //ui->showInfo->appendPlainText(tr("recv:")+QString::number(size));
        fwrite(&recv_buf[place],1,size,rfp);
    }
    else if(cmp_str(recv_buf,"#*#clientend")) {
        ui->showInfo->appendPlainText(str);
        fclose(rfp);
    }
    else if(cmp_str(data,"#*#dir")) {

        getDirInfo("tempxxx.txt");
        send_file("tempxxx.txt","show");
        QFile temp("tempxxx.txt");
        temp.remove();
    }
    else{
        ui->showInfo->appendPlainText(str);
        if(cmp_str(data,"#*#open"))
        {
            char dstFilename[1000];
            getSubStr(data,dstFilename,1);
            detectName(dstFilename);
            sprintf(dstFilename,"%s",dstFilename);
            QString cmd = QString("file:///") + tr(dstFilename);
            bool is_open = QDesktopServices::openUrl(QUrl(cmd, QUrl::TolerantMode));
            if(!is_open)
            {
                ui->showInfo->appendPlainText(tr("open failed!"));
            }
        }
        else
        {
            char cmd[1024];
            sprintf(cmd,"%s >tempxxx.txt",&data[3]);
            system(cmd);
            send_file("tempxxx.txt","show");
            QFile temp("tempxxx.txt");
            temp.remove();
        }
//        data[50]='\0';
//        ui->showInfo->appendPlainText(tr("else:")+tr(data));

//        QString tdir = QDir::currentPath();
//        QTextCodec::setCodecForLocale(QTextCodec::codecForName("GB2312"));
//        QByteArray temp1 = tdir.toLocal8Bit();
//        char *path = temp1.data();
//        sprintf(send_buf,"#*#dir %s",path);
//        QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
//        this->send_str(send_buf);
    }

    return true;
}



void MainWindow::on_start_clicked()
{
    //ui->showInfo->setText();
    //监听套接字   指定父对象的目的，让其自动回收空间
    if(isOpen )
        return ;
   
    isOpen = true;
    tcpServer = new QTcpServer(this);
    tcpServer->listen(QHostAddress::Any,8123);

    recvLen = 0;
    ui->showInfo->appendPlainText(tr("start server"));
    connect(tcpServer,&QTcpServer::newConnection,[=](){
        //取出建立好连接的的套接字
        tcpSocket = tcpServer->nextPendingConnection();

        //获取对方的IP和端口
        QString ip = tcpSocket->peerAddress().toString();
        qint16  port = tcpSocket->peerPort();
        QString temp = QString("Client: [%1:%2]").arg(ip).arg(port);

        ui->showInfo->appendPlainText(temp);

        connect(tcpSocket, &QTcpSocket::readyRead,[=](){
            //获取对方发送的内容
//            char buf[1024];
//            int size = tcpSocket->read(buf,1024);
//            ui->showInfo->appendPlainText(tr("size: ")+QString::number(size));
//            //if(size == 1024)
//             server_recv(buf);

              QByteArray buf = tcpSocket->readAll();
              char *temp = buf.data();
//              ui->showInfo->appendPlainText(tr("size: ")+QString::number(buf.size())+tr(" ")+QString::number(buf.size()%1024));
              for(int i=0;i<buf.size();i++)
              {
                  recvBuf[recvLen]=temp[i];
                  recvLen++;
                  if(recvLen==1024)
                  {
                      char data[1024];
                      for(int n=0;n<1024;n++)
                          data[n]=recvBuf[n];
                      recvLen=0;
                      server_recv(data);
                  }

              }

         });

        QTextCodec::setCodecForLocale(QTextCodec::codecForName("GB2312"));
        QString str= QDir::currentPath();
        QByteArray temp1 = str.toLocal8Bit();
        const char *path = temp1.data();
        char send_buf[1024];
        sprintf(send_buf,"#*#dir %s",path);
        tcpSocket->write(send_buf, 1024);
        ui->showInfo->appendPlainText(str);
        QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));

    });
}



void MainWindow::on_start2_clicked()
{

    ui->showInfo->appendPlainText(tr("close server"));
    if(NULL == tcpSocket)
    {
        return ;
    }
    //主动和客户端端口断开连接
    tcpSocket->disconnectFromHost();
    tcpSocket->close();

    tcpSocket = NULL;
}

void MainWindow::on_start_2_clicked()
{

}



void MainWindow::on_start_3_clicked()
{

}

void MainWindow::on_pushButton_clicked()
{
    QAndroidJniEnvironment env;
    QAndroidJniObject activity = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/android/QtNative", "activity", "()Landroid/app/Activity;");

    if(lightOn)
    {
        if(m_wakeLock.isValid())
        {
            m_wakeLock.callMethod<void>("release");
            if(env->ExceptionCheck())
            {
                ui->showInfo->appendPlainText("callObjectMethod 0 wrong!");
                env->ExceptionClear();
            }
        }
        lightOn = false;
        ui->pushButton->setText(tr("Dark"));
        return;
    }
    lightOn=true;
    ui->pushButton->setText(tr("Light"));

    QAndroidJniObject name = QAndroidJniObject::getStaticObjectField(
                "android/content/Context",
                "POWER_SERVICE",
                "Ljava/lang/String;"
                );
    if(env->ExceptionCheck())
    {
        ui->showInfo->appendPlainText("get POWER_SERVICE wrong!");
        env->ExceptionClear();
        return ;
    }
    QAndroidJniObject powerService = activity.callObjectMethod(
                "getSystemService",
                "(Ljava/lang/String;)Ljava/lang/Object;",
                name.object<jstring>());

    if(env->ExceptionCheck())
    {
        ui->showInfo->appendPlainText("callObjectMethod 1 wrong!");
        env->ExceptionClear();
        return ;
    }

    QAndroidJniObject tag = QAndroidJniObject::fromString("QtJniWakeLock");
    m_wakeLock = powerService.callObjectMethod(
                "newWakeLock",
                "(ILjava/lang/String;)Landroid/os/PowerManager$WakeLock;",
                10, //SCREEN_BRIGHT_WAKE_LOCK
                tag.object<jstring>()
                );

    if(env->ExceptionCheck())
    {
        ui->showInfo->appendPlainText("callObjectMethod 2 wrong!");
        env->ExceptionClear();
        return ;
    }

    if(m_wakeLock.isValid())
    {
        m_wakeLock.callMethod<void>("acquire");
        if(env->ExceptionCheck())
        {
            ui->showInfo->appendPlainText("callObjectMethod 3 wrong!");
            env->ExceptionClear();
        }
    }
}
